package handler

import (
	"strconv"
	"strings"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssforward/common/constant"
	"ssforward/common/utils"
	"ssforward/internal/forward/models"
)

type HttpForwardHandler struct {
	Orm *gorm.DB
}

func (e *HttpForwardHandler) ForwardData(ruleConfig map[string]interface{}, jsonData map[string]interface{}) {
	serverObj, ok := ruleConfig["server"]
	if !ok || serverObj == nil {
		return
	}
	server := serverObj.(map[string]interface{})
	serverId := server["id"].(string)
	// 转发地址
	host := utils.GetStringValueFiled(server, "host")
	port := utils.GetIntValueFiled(server, "port")
	url := utils.GetStringValueFiled(server, "url")
	url = utils.If(strings.HasPrefix(url, "/"), "", "/").(string) + url
	url += utils.GetStringValueFiled(jsonData, constant.UrlSuffixField)
	delete(jsonData, constant.UrlSuffixField)
	url = strings.ReplaceAll(url, "//", "/")
	if !strings.HasPrefix(host, "http") {
		host = strings.ReplaceAll(host, "http://", "")
		host = strings.ReplaceAll(host, "https://", "")
		host = "http://" + host
	}
	httpUrl := host + ":" + strconv.Itoa(port) + url
	contType := utils.GetStringValueFiled(server, "contentType")
	// 转发数据
	mapData := dataToMap(ruleConfig["variableMap"].(map[string]interface{}), jsonData)
	if len(mapData) > 0 {
		jsonData = mapData
	}
	// 非阻塞请求
	go func() {
		header := make(map[string]string)
		var resultJson interface{}
		if err := utils.HttpPost(httpUrl, jsonData, header, &resultJson, contType); err != nil {
			_ = env.Cache.HashSet(constant.ForwardClientPrefix+serverId, map[string]interface{}{constant.ForwardClientStatus: "false"})
			logger.Errorf("http数据转发异常 url=[%v] jsonBody=[%+v] responseBody=[%+v] err=[%+v]", httpUrl, utils.InterfaceToStr(jsonData), utils.InterfaceToStr(resultJson), err)
		} else {
			_ = env.Cache.HashSet(constant.ForwardClientPrefix+serverId, map[string]interface{}{constant.ForwardClientLastTime: utils.GetNowTimeStr(), constant.ForwardClientStatus: "true"})
			_, _ = env.Cache.HIncrBy(constant.ForwardClientPrefix+serverId, constant.ForwardClientSendCount, 1)
			logger.Debugf("http数据转发成功serverId=[%v], url=[%v], responseBody=[%+v]", serverId, httpUrl, utils.InterfaceToStr(resultJson))
			addToDetail(serverId)
		}
	}()
}

// 测试连接
func TestHttpConnect(serverItem models.SysForwardServer) (err error) {
	url := serverItem.Url
	url = utils.If(strings.HasPrefix(url, "/"), "", "/").(string) + url
	host := serverItem.Host
	if !strings.HasPrefix(host, "http") {
		host = strings.ReplaceAll(host, "http://", "")
		host = strings.ReplaceAll(host, "https://", "")
		host = "http://" + host
	}
	httpUrl := host + ":" + strconv.Itoa(serverItem.Port) + url
	param := map[string]interface{}{}
	header := make(map[string]string)
	var resultJson interface{}
	if ee := utils.HttpPost(httpUrl, param, header, &resultJson, serverItem.ContentType); ee != nil && !strings.Contains(ee.Error(), "unexpected end of JSON input") {
		return ee
	}
	return
}
